package com.woniuxy.shop.servelet.front;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.woniuxy.shop.entity.Address;
import com.woniuxy.shop.entity.DetailOrder;
import com.woniuxy.shop.entity.Goods;
import com.woniuxy.shop.entity.Order;
import com.woniuxy.shop.entity.PageBean;
import com.woniuxy.shop.entity.PreOrder;
import com.woniuxy.shop.entity.ResponseEntity;
import com.woniuxy.shop.entity.User;
import com.woniuxy.shop.entity.UserCenter;
import com.woniuxy.shop.exception.ServiceException;
import com.woniuxy.shop.exception.StockIsEnnoughException;
import com.woniuxy.shop.service.AddressService;
import com.woniuxy.shop.service.CartService;
import com.woniuxy.shop.service.GoodsService;
import com.woniuxy.shop.service.OrderService;
import com.woniuxy.shop.service.ServiceProxyFactory;
import com.woniuxy.shop.utils.ShopUtils;

/**
 * Servlet implementation class CateGoryServelet
 */
@WebServlet("/order")
public class FOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	OrderService os = ServiceProxyFactory.getProxy(OrderService.class);
	GoodsService gs = new GoodsService();
	AddressService as = new AddressService();
	CartService cs = new CartService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		if ("initialAdd".equals(opr)) {
			doInitialAdd(request, response);
		}else if("add".equals(opr)) {
			doAdd(request, response);
		}else if("query".equals(opr)) {
			doQuery(request, response);
		}
		
	}
	
	

	/**
	 * 查询未支付的最近5笔订单
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void doQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ResponseEntity<UserCenter> rese = new ResponseEntity<>();
		UserCenter uc = new UserCenter();
		User u  = (User)request.getSession().getAttribute("user");
		if(u==null) {
			rese.setCode(102);
			rese.setMsg("error");
			ShopUtils.write(response, rese);
			return;
		}
		try {
			List<Order> orders = os.getRecentOrders(u.getId());
			rese.setCode(200);
			rese.setMsg("ok");
			uc.setUser(u);
			uc.setOrders(orders);
			rese.setData(uc);
			ShopUtils.write(response, rese);
		} catch (Exception e) {
			rese.setCode(101);
			rese.setMsg("error");
			ShopUtils.write(response, rese);
		}
		
	}




	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int addressid = Integer.parseInt(request.getParameter("order.address.id"));//获取地址id
		String deliveryType = request.getParameter("order.deliveryType");//快递方式
		String payType =request.getParameter("order.payType");//支付方式
		String deliveryTime =request.getParameter("order.deliveryTime");//支付方式
		int i=0;
		List<DetailOrder> dors = new ArrayList<DetailOrder>();
		while(true) {
			String name = "orderDetails"+i+"goodsid";
			String snum = "orderDetails"+i+"nums";
			
			String sgid = request.getParameter(name); 
			String sgnum = request.getParameter(snum);
			if(sgid==null||snum==null) {
				break;
			}
			int num = Integer.parseInt(sgnum);
			Goods g = gs.getGoods(Integer.parseInt(sgid));
			DetailOrder  dor = new DetailOrder();
			dor.setGoodsid(g.getId());
			dor.setPrice(g.getSaleprice()*num);
			dor.setNums(num);
			dors.add(dor);
			i++;
			System.out.println(dor);
		}
		
		//将dors转换成数组
		DetailOrder[] arrDetailOrder = new DetailOrder[dors.size()];
		for(int j=0;j<dors.size();j++) {
			arrDetailOrder[j] = dors.get(j);
		}
		//设置订单相关属性
		Order o  = new Order();
		String addTime = ShopUtils.getNowTimeNoSymbol();
		Address a = as.getAddressById(addressid);
		ShopUtils.setTopName(a);
		String receiveinfo = "收件人:"+a.getAccepter()+";地址："+
			a.getProvience()+a.getCity()+a.getArea()+a.getDetailArea()+
			";电话号码："+a.getTelephone()+";快递方式:"+deliveryType+";支付方"
			+ "式："+payType+";配送时间："+deliveryTime+";";
		double deliveryMoney = 0;
		if(deliveryType.equals("EMS")) {
			deliveryMoney=10;
		}else {
			deliveryMoney=20;
		}
		o.setReceiveinfo(receiveinfo);
		o.setUserid(a.getUserid());
		o.setOrdertime(addTime);
		o.setMoney(deliveryMoney);
		o.setPaytype(payType);
		o.setStatus("待付款");
		try {
			os.add(o, arrDetailOrder);
			
			//删除购物车的数据
			int k=0;
			while(true) {
				String cname = "orderDetails"+k+"cartid";
				String cvalue = request.getParameter(cname);
				if(cvalue==null) {
					break;
				}
				int cartid = Integer.parseInt(cvalue);
				if(cartid!=0) {//如果不是0则证明来自购物车
					cs.del(cartid);
				}
				k++;
			}
		} catch (ServiceException e) {
			if(e.getCause() instanceof StockIsEnnoughException) {
				request.setAttribute("errorOrder", e.getMessage());
			}else {
				request.setAttribute("errorOrder", "系统维护中,添加订单失败，请稍后再试");
			}
			request.getRequestDispatcher("order?opr=initialAdd").forward(request, response);
		}

		Order orderAfterAdd = os.getNewOrder();//可能有bug
		request.setAttribute("order", orderAfterAdd);
		request.getRequestDispatcher("order_submit.jsp").forward(request, response);
	}




	private void doInitialAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		//有可能来自登陆界面，里面会自带预订单信息
		
		List<PreOrder> pos = (List<PreOrder>)request.getAttribute("List<PreOrder>");
		if(pos==null) {
			//若pos为null则证明来自购物车
			//获取预订单相关信息
			//商品的数量和id的格式为:goodsnum,goodsid
			String[] sdatas = request.getParameterValues("checks");
			 pos = new ArrayList<>();
			if(sdatas!=null) {
				for (String sdata : sdatas) {
					//将字符串拆分，第一项为num，后一项为数量
					String[] infos = sdata.split(",");
					int goodsnum = Integer.parseInt(infos[0]);
					int goodsid = Integer.parseInt(infos[1]);
					int cartid = Integer.parseInt(infos[2]);
					Goods g = gs.getGoods(goodsid);
					//创建预订单
					PreOrder po =  new PreOrder();
					if(g!=null) {
						po.setG(g);
					}
					po.setGoogsNum(goodsnum);
					po.setCartId(cartid);
					pos.add(po);
				}
				request.setAttribute("orderDetails", pos);
			}
		}
		
		
		
		//获取用户相关信息
		User u = (User)request.getSession().getAttribute("user");
		if(u==null) {
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		
		List<Address> addresses = ShopUtils.getAddresses(u.getId());
		request.setAttribute("addresses", addresses);
		request.getRequestDispatcher("order_add.jsp").forward(request, response);
			
		
	}




	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
}
